package com.quectel.cms.controller.carparking;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.carparking.dto.CarParkingDto;
import com.quectel.core.module.carparking.dto.CarParkingSpaceDto;
import com.quectel.core.module.carparking.service.CarParkingService;
import com.quectel.core.module.carparking.service.CarParkingSpaceLogService;
import com.quectel.core.module.carparking.service.CarParkingSpaceService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author bobo
 * @email bob.yu@quectel.com
 * @date 2022/02/22 09:45
 */
@RestController
@RequestMapping("carParkingSpace")
@Tag(name = "CarParkingSpaceController", description = "停车场车位管理表相关api")
public class CarParkingSpaceController extends BaseController {

    @DubboReference
    private CarParkingSpaceService carParkingSpaceService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private CarParkingService carParkingService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageRoomService villageRoomService;
    @DubboReference
    private CarParkingSpaceLogService carParkingSpaceLogService;

    /**
     * 列表
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "carParkingSpace:importExcel")
    @Operation(summary = "导入车位信息")
    @Log(express = "导入车位信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        LoginUserSession sysUser = SessionHolder.getSysUser();
        Date now = new Date();
        List<CarParkingSpaceDto> list = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    for (Map<Integer, String> map : analysis) {
                        try {
                            VillageDto villageDto = villageService.selectByName(sysUser.getTenantId(), map.get(0));
                            if (villageDto == null || !Objects.equals(villageDto.getTenantId(), SessionHolder.getSysUser().getTenantId())) {
                                continue;
                            }

                            CarParkingSpaceDto dto = new CarParkingSpaceDto();
                            dto.setVillageId(villageDto.getId());
                            CarParkingDto carParkingDto = carParkingService.selectByName(sysUser.getTenantId(), map.get(1));
                            dto.setCarParkingId(carParkingDto.getId());
                            dto.setName(map.get(2));
                            dto.setSize(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CAR_PARKING_SPACE_SIZE, map.get(3), Byte.class));
                            dto.setCode(map.get(4));
                            dto.setType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CAR_PARKING_SPACE_TYPE, map.get(5), Byte.class));
                            dto.setEquityCode(map.get(6));
                            dto.setState(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CAR_PARKING_SPACE_STATE, map.get(7), Byte.class));
                            dto.setUsageType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CAR_PARKING_SPACE_USAGE, map.get(8), Byte.class));
                            dto.setHouseholdName(map.get(9));
                            Long buildingDtoId = null;
                            String villageBuildingName = map.get(10);
                            String roomName = map.get(12);
                            if (StringUtils.isNotEmpty(villageBuildingName) && StringUtils.isNotEmpty(roomName)){
                                VillageBuildingDto villageBuildingDto = villageBuildingService.selectByName(villageDto.getId(), villageBuildingName);
                                if (villageBuildingDto == null) {
                                    continue;
                                } else {
                                    // 单元id
                                    buildingDtoId = villageBuildingDto.getId();
                                }
                                if (!roomName.contains("室")) {
                                    roomName = map.get(12) + "室";
                                }
                                VillageRoomDto villageRoomDto = villageRoomService.selectByNameWithBuildingId(buildingDtoId, roomName);
                                if (villageRoomDto != null) {
                                    dto.setHouseholdRoomId(villageRoomDto.getId());
                                }
                            }

                            dto.setMobile(map.get(13));
                            String licensesArray = map.get(14);
                            if (StringUtils.isNotEmpty(licensesArray)){
                                String[] licenses = map.get(14).split(",");
                                dto.setLicenses(JacksonUtils.toJsonString(licenses));
                            }else {
                                List<String> emtryList = new ArrayList<>();
                                dto.setLicenses(JacksonUtils.toJsonString(emtryList));
                            }

                            dto.setCreateTime(now);

                            if (StringUtils.isBlank(dto.getName())) {
                                continue;
                            }

                            fillSaveCommonData(dto);
                            list.add(dto);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析导入信息出错");
                }
            }
        }
        int successCount = 0;
        for (CarParkingSpaceDto dto : list) {
            try {
                successCount++;
                CarParkingSpaceDto dbValue = carParkingSpaceService.selectOne(dto.getCarParkingId(), dto.getCode());
                if (dbValue != null) {
                    continue;
                }
                carParkingSpaceService.save(dto);
            } catch (Exception e) {
                logger.error("导入失败", e);
                continue;
            }
        }
        return Response.error("导入成功,导入成功数量为:" + successCount);
    }

    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "carParkingSpace:exportExcel")
    @Operation(summary = "导出车位信息")
    @Log(express = "导出车位信息")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<CarParkingSpaceDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<CarParkingSpaceDto> list = carParkingSpaceService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "停车场名称", "车位类型", "车位状态", "车位用途", "车位名称", "车位编码", "车位产权编码"};
        List<String[]> dataList = new ArrayList<>();
        for (CarParkingSpaceDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[1] = data.getCarParking() != null ? data.getCarParking().getName() : null;
            item[2] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CAR_PARKING_SPACE_TYPE, data.getType() + "");
            item[3] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CAR_PARKING_SPACE_STATE, data.getState() + "");
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CAR_PARKING_SPACE_USAGE, data.getUsageType() + "");
            item[5] = data.getName();
            item[6] = data.getCode();
            item[7] = data.getEquityCode();
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "车位信息", headers, dataList, "车位信息");
    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "carParkingSpace:list")
    @Operation(summary = "分页列表")
    public Response<Page<CarParkingSpaceDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = carParkingSpaceService.queryTotal(request.getParams());

        List<CarParkingSpaceDto> list = null;
        if (total > 0) {
            list = carParkingSpaceService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<CarParkingSpaceDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<CarParkingSpaceDto>>ok().wrap(page);
    }


    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "carParkingSpace:edit")
    @Operation(summary = "查询单条记录")
    public Response<CarParkingSpaceDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (carParkingSpaceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        CarParkingSpaceDto carParkingSpaceDto = carParkingSpaceService.selectById(id);

        return Response.<CarParkingSpaceDto>ok().wrap((carParkingSpaceDto));
    }

    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "carParkingSpace:info")
    @Operation(summary = "查询单条记录")
    public Response<CarParkingSpaceDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (carParkingSpaceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        CarParkingSpaceDto carParkingSpaceDto = carParkingSpaceService.selectById(id);

        return Response.<CarParkingSpaceDto>ok().wrap((carParkingSpaceDto));
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "carParkingSpace:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated CarParkingSpaceDto carParkingSpaceDto) {

        //填充基础数据
        fillSaveCommonData(carParkingSpaceDto);

        CarParkingSpaceDto dbValue = carParkingSpaceService.selectOne(carParkingSpaceDto.getCarParkingId(), carParkingSpaceDto.getCode());
        if (dbValue != null) {
            return Response.error("该停车场车位编码已被占用");
        }

        if (carParkingSpaceDto.getHouseholdRoomId()!=null){
            VillageRoomDto villageRoomDto = villageRoomService.selectCacheById(carParkingSpaceDto.getHouseholdRoomId());
            if (!villageRoomDto.getVillageId().equals(carParkingSpaceDto.getVillageId())){
                return Response.error("选择的停车场和房屋不在一个小区，请重新选择");
            }
        }

        carParkingSpaceService.save(carParkingSpaceDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "carParkingSpace:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated CarParkingSpaceDto carParkingSpaceDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(carParkingSpaceDto.getId()));
        if (carParkingSpaceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        CarParkingSpaceDto dbValue = carParkingSpaceService.selectOne(carParkingSpaceDto.getCarParkingId(), carParkingSpaceDto.getCode());
        if (dbValue != null && !Objects.equals(carParkingSpaceDto.getId(), dbValue.getId())) {
            return Response.error("该停车场车位编码已被占用");
        }

        if (carParkingSpaceDto.getHouseholdRoomId()!=null){
            VillageRoomDto villageRoomDto = villageRoomService.selectCacheById(carParkingSpaceDto.getHouseholdRoomId());
            if (!villageRoomDto.getVillageId().equals(carParkingSpaceDto.getVillageId())){
                return Response.error("选择的停车场和房屋不在一个小区，请重新选择");
            }
        }

        //填充基础数据
        fillEditCommonData(carParkingSpaceDto);

        CarParkingSpaceDto sqlData = carParkingSpaceService.selectById(carParkingSpaceDto.getId());

        carParkingSpaceService.updateById(carParkingSpaceDto);

        // 如果信息变更 1.车位状态  2.出租人/出售人 3.联系方式 4.所属房屋 5.登记车牌号码 变更就保存记录
        if (!sqlData.getState().equals(carParkingSpaceDto.getState())
                || !sqlData.getHouseholdName().equals(carParkingSpaceDto.getHouseholdName()) || !sqlData.getMobile().equals(carParkingSpaceDto.getMobile())
                || (sqlData.getHouseholdRoomId()!=null && !sqlData.getHouseholdRoomId().equals(carParkingSpaceDto.getHouseholdRoomId()))
                || !sqlData.getLicenses().equals(carParkingSpaceDto.getLicenses())) {

            carParkingSpaceService.saveCarParkingSpaceChangeLog(carParkingSpaceDto);
        }

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "carParkingSpace:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (carParkingSpaceService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        carParkingSpaceService.deleteBatch(ids);

        return Response.ok();
    }
}
